package com.example.linearlayoutdemo.networkstate;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

// 1. 定义系统广播接收器（监听网络变化）
public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 2. 判断是否是网络变化的广播（Android 8.0+ 需显式判断，避免其他广播干扰）
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            // 3. 获取网络连接管理器，判断当前网络状态
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

            // 4. 处理网络状态：有网/无网
            if (activeNetwork != null && activeNetwork.isConnected()) {
                // 有网络（区分 WiFi/流量）
                String networkType = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI
                        ? "WiFi" : "移动数据";
                Toast.makeText(context, "网络已连接：" + networkType, Toast.LENGTH_SHORT).show();
            } else {
                // 无网络
                Toast.makeText(context, "网络已断开，请检查连接", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
